package com.firewolf.rabbitmq;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import utils.ConnectionUtils;

public class UserClient {
	private static Connection connection;
	private static Channel channel;
	private static String requestQueueName = "rpc_queue";
	private static String replyQueueName;

	public static void main(String[] args) throws Exception {
		connection = ConnectionUtils.getMQConnection();
		channel = connection.createChannel();
		replyQueueName = channel.queueDeclare().getQueue();
		String call = call("liuxing");
		System.out.println(call);
	}

	/**
	 * 远程调用
	 * @param message
	 * @return
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static String call(String message) throws IOException, InterruptedException {
		//这个使用来标识请求的
		final String corrId = UUID.randomUUID().toString();

		AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName)
				.build();

		channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8"));

		final BlockingQueue<String> response = new ArrayBlockingQueue<String>(1);

		channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				if (properties.getCorrelationId().equals(corrId)) {
					response.offer(new String(body, "UTF-8"));
				}
			}
		});

		return response.take();
	}

	public void close() throws IOException {
		connection.close();
	}
}
